from bs4 import BeautifulSoup
import urllib.request
import os

def downloadimg(url,m,n):
    os.chdir(os.path.join(os.getcwd(),'photos'))#锁定目录到当前目录的photots文件夹下
    t = 1 #记录图片张数

    for x in range(n - m + 1):
        html_doc = urllib.request.urlopen(url).read().decode('utf-8')
        soup = BeautifulSoup(html_doc,"lxml")

        for myimg in soup.find_all('a',class_='a',target='_blank'):
            pic_name = str(t)+'.jpg'#拼接出图片的名字
            img_src = myimg.get('href')#获取图片的url
           # urllib.request.urlretrieve(img_src,pic_name)
            img_src="https://www.duitang.com"+img_src
            html_doc = urllib.request.urlopen(img_src).read().decode('utf-8')
            soup = BeautifulSoup(html_doc,'lxml')
            img_src = soup.find('a',class_='img-out',target='_blank')
            img_src = img_src.find('img').get('src')
            urllib.request.urlretrieve(img_src,pic_name)
            t += 1
        print("next")

downloadimg("http://www.duitang.com/search/?kw=%E7%82%B9%E5%85%94&type=feed",1,2)
